package com.xyd.Servlet;

import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.config.AlipayConfig;
import com.xyd.Biz.CommodityBiz;
import com.xyd.Biz.FatherOrderBiz;
import com.xyd.Biz.Impl.CommodityBizImpl;
import com.xyd.Biz.Impl.FatherOrderBizImpl;
import com.xyd.Biz.Impl.OrderFormBizImpl;
import com.xyd.Biz.Impl.ProductCarBizImpl;
import com.xyd.Biz.OrderFormBiz;
import com.xyd.Biz.ProductCarBiz;
import com.xyd.Entity.FatherOrder;
import com.xyd.Entity.OrderForm;
import com.xyd.Entity.ProductCar;
import com.xyd.Entity.User;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: NotifyServlet
 * @Description:
 * @Author 余全盛
 * @Date: 2021/10/18 15:20
 */
@WebServlet("/ReturnServlet")
public class ReturnServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        PrintWriter out = response.getWriter();
        long id = 0;
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            id = Long.parseLong(out_trade_no);
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            out.println("trade_no:" + trade_no + "<br/>out_trade_no:" + out_trade_no + "<br/>total_amount:" + total_amount);
        } else {
            out.println("验签失败");
        }
        //支付完成时，修改订单状态
        FatherOrderBiz fatherOrderBiz = new FatherOrderBizImpl();
        fatherOrderBiz.updateFatherOrderState(1, id);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //支付完成时，库存修改
        OrderFormBiz orderFormBiz = new OrderFormBizImpl();
        List<OrderForm> list = orderFormBiz.selectSonOrder(id);
        CommodityBiz commodityBiz = new CommodityBizImpl();
        for (OrderForm orderForm : list) {
            orderFormBiz.updateSonOrderState(1,orderForm.getSonorderid());
            commodityBiz.updateCommodityInventory(orderForm.getNum(), orderForm.getCom_id());
        }
        //支付完成时，删除购物车中已支付商品
        ProductCarBiz productCarBiz = new ProductCarBizImpl();
        productCarBiz.deleteAllPayedProductCar(user.getUserid());
        response.sendRedirect("/shopping/TodaySpecialsServlet");
    }

}
